package com.young.service;

import com.young.domain.Member;
import com.young.domain.MemberMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @author: create by Young
 * @version: v1.0
 * @description: com.young.service
 * @date:2019/3/17 3:18
 */
@Service(value="userDetailService")
public class UserDetailService implements UserDetailsService {

	@Autowired
	private MemberMapper memberMapper;

	public UserDetailService(MemberMapper m) {
		this.memberMapper = m;

		//先注册一个账号用来测试，使用BCrypt加密
		String name = "test";
		BCryptPasswordEncoder encoder =new BCryptPasswordEncoder();
		String password = encoder.encode("111");
		memberMapper.createMember(name,password);
	}

	@Override
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
		Member member = memberMapper.findByName(username);
		if(member == null) throw new UsernameNotFoundException("用户不存在");
		List<GrantedAuthority> list = new ArrayList<GrantedAuthority>();
		getRoles(member,list);
		User auth_member = new User(member.getUsername(),member.getPassword(),list);

		return auth_member;
	}

	public void getRoles(Member member,List<GrantedAuthority> list) {
		for(String role:member.getRole().split(",")) {
			//权限如果前缀是ROLE_，security就会认为这是个角色信息，而不是权限，
			//例如ROLE_MENBER就是MENBER角色，CAN_SEND就是CAN_SEND权限
			list.add(new SimpleGrantedAuthority("ROLE"+role));
		}
	}
}
